package com.bw.trade.service.impl;

import cn.hutool.core.lang.Snowflake;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bw.core.creditStatus.RefundBorrowStatus;
import com.bw.core.exception.BaseException;
import com.bw.core.utils.HttpClientUtils;
import com.bw.core.utils.MD5Sign;
import com.bw.core.vo.FindOneBankResVo;
import com.bw.core.vo.FindOneOrderResVo;
import com.bw.core.vo.OrderRiskVO;
import com.bw.trade.fegin.FeginBillClient;
import com.bw.trade.fegin.FeginUserClient;
import com.bw.trade.pojo.TbBorrowLog;
import com.bw.trade.mapper.TbBorrowLogMapper;
import com.bw.trade.service.TbBorrowLogService;
import com.bw.trade.vo.FanHuiVo;
import org.omg.CORBA.Environment;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


/**
 * <p>
 * 借款记录表 服务实现类
 * </p>
 *
 * @author lv
 * @since 2021-03-23
 */
@Service
@SuppressWarnings("all")
@Component
public class TbBorrowLogServiceImpl extends ServiceImpl<TbBorrowLogMapper, TbBorrowLog> implements TbBorrowLogService {

    @Autowired
    private TbBorrowLogMapper borrowLogMapper;
    @Autowired
    private FeginBillClient billClient;
    @Autowired
    private FeginUserClient userClient;
    @Autowired
    private Snowflake snowflake;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private TbBorrowLogService tbBorrowLogService;
    @Autowired
    private Environment env;

    //第三方放款接口
    public void callMethod(OrderRiskVO orderRiskVO, TbBorrowLog borrowLog) {

        HashMap<String,Object> map = new HashMap<>();

        String merId = "1001";
        String appSercret = "aea43111aa87807fb79939b28256b929";
        //将调用易宝放款平台所需要的参数放入map集合
        map.put("merId", merId);
        map.put("sign", appSercret);
        map.put("name", orderRiskVO.getUserName());
        map.put("cardId", orderRiskVO.getUserIdentityNo());
        map.put("accNo", borrowLog.getTargetAccount());
        map.put("bankName", borrowLog.getBankName());
        map.put("bankShortName", borrowLog.getBankShortName());
        map.put("merTradeNo", borrowLog.getOrderNo());
        map.put("amount", borrowLog.getPayAmount().toString());
        map.put("notifyUrl", "上海");

        String s = HttpUtil.post("http://localhost:8080/api/common/collectionConfirm", map);
        if (StrUtil.hasBlank(s)) {
            throw new BaseException("调用第三方接口失败");
        }

        JSONObject jsonObject = JSON.parseObject(s);
        JSONObject data = jsonObject.getJSONObject("data");
        if (jsonObject.getInteger("code").intValue() != 0) {
            throw new BaseException("失败");
        }
        String message = jsonObject.getString("message");
        String thirdTradeNo = data.getString("thirdTradeNo");//返回的三方交易单号
        String resCode = data.getString("resCode");

        TbBorrowLog tbBorrowLog = new TbBorrowLog();
        tbBorrowLog.setId(borrowLog.getId());
        tbBorrowLog.setOutTradeNo(thirdTradeNo);
        tbBorrowLog.setReturnCode(resCode);
        tbBorrowLog.setReturnMsg(message);

        borrowLogMapper.updateById(tbBorrowLog);//修改状态

    }

    //根据交易单号查询结果(定时任务查询)
    @Scheduled(fixedRate = 5000)
    public List<TbBorrowLog> searchOrder() {
        System.out.println("定时器开启");

        //查询所有状态为处理中的记录
        QueryWrapper<TbBorrowLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("borrow_status",RefundBorrowStatus.REFUND_BORROW_CHECK_RUNNING);
        List<TbBorrowLog> tbBorrowLogs = borrowLogMapper.selectList(queryWrapper);
       //用不用判断集合为空
        tbBorrowLogs.forEach(a->{
            HashMap<String, String> map = new HashMap<>();
            map.put("merId", snowflake.nextIdStr() + "");
            map.put("sign", MD5Sign.md5Encode( "abc..."));
            map.put("thirdTradeNo",a.getOutTradeNo());
            String s = HttpClientUtils.httpPost("http://localhost:8080/api/common/queryTradeResult", map);
            if (StrUtil.hasBlank(s)) {
                throw new BaseException("调用第三方接口失败");
            }
            JSONObject jsonObject = JSON.parseObject(s);
            JSONObject data1 = jsonObject.getJSONObject("data");
            if(jsonObject.getInteger("code").intValue()!=0){
                return;
            }
            String msgInfo1 = data1.getString("msgInfo");
            String thirdTradeNo1 = data1.getString("thirdTradeNo");
            String resCode = data1.getString("resCode");//返回Code
            if(resCode!="1001"){
                return;
            }
            QueryWrapper<TbBorrowLog> wrapper = new QueryWrapper<>();
            wrapper.eq("out_trade_no",a.getOutTradeNo());
            TbBorrowLog tbBorrowLog = borrowLogMapper.selectOne(queryWrapper);

            FanHuiVo fanHuiVo1 = new FanHuiVo();
            fanHuiVo1.setOrderNo(tbBorrowLog.getOrderNo());
            fanHuiVo1.setStartDate(new Date());

            String s1 = JSON.toJSONString(fanHuiVo1);
            amqpTemplate.convertAndSend("item_plan",s1);//推送信息给业务

            TbBorrowLog tbBorrowLog1 = new TbBorrowLog();
            tbBorrowLog1.setId(tbBorrowLog.getId());
            tbBorrowLog1.setBorrowStatus(RefundBorrowStatus.REFUND_BORROW_SUCCESS);
            borrowLogMapper.updateById(tbBorrowLog1);
        });

        return tbBorrowLogs;

    }

}






